import { QrcodeconfigService } from './../../../../@core/services/QRCodeConfig/qrcodeconfig.service';
import { QRCodeConfig } from 'src/app/@core/data/QRCodeConfig';
import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import {
  DialogService,
  DValidateRules,
  FormLayout,
  TableWidthConfig,
} from 'ng-devui';
import { PurchaseArrivalOrder } from 'src/app/@core/data/purchase';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { DataSharingService } from 'src/app/@core/services/dataSharing/data-sharing.service';
import { PurchaseService } from 'src/app/@core/services/purchase/purchase.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { SelectSupplierComponent } from 'src/app/@shared/components/select-supplier/select-supplier.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { environment } from 'src/environments/environment';
import { SelectRequireComponent } from '../../purchase-order/select-require/select-require.component';
import { SelectInventoryComponent } from 'src/app/@shared/components/select-inventory/select-inventory.component';
import { SelectPurchaseOrderComponent } from '../select-purchase-order/select-purchase-order.component';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { MaterialService } from 'src/app/@core/services/material/material.service';
import { SelectPositionComponent } from 'src/app/@shared/components/select-position/select-position.component';
import { SelectStorehouseComponent } from 'src/app/@shared/components/select-storehouse/select-storehouse.component';

@Component({
  selector: 'app-purchase-arrival-edit',
  templateUrl: './purchase-arrival-edit.component.html',
  styleUrls: ['./purchase-arrival-edit.component.scss'],
})
export class PurchaseArrivalEditComponent {
  Math = Math;
  msgs: Array<Object> = [];
  UrlHead: any = environment.modifiedApiUrl;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px',
    },
    {
      field: '物料编码',
      width: '150px',
    },
    {
      field: '图片',
      width: '150px',
    },
    {
      field: '物料名称',
      width: '150px',
    },
    {
      field: '物料规格',
      width: '150px',
    },
    {
      field: '物料描述',
      width: '150px',
    },
    {
      field: '物料单位',
      width: '150px',
    },
    {
      field: '到货日期',
      width: '200px',
    },
    {
      field: '仓库',
      width: '200px',
    },
    {
      field: '库位',
      width: '200px',
    },
    {
      field: '入库数量',
      width: '200px',
    },
    {
      field: '单价(含税)',
      width: '200px',
    },
    {
      field: '税率',
      width: '200px',
    },
    {
      field: '不含税单价',
      width: '150px',
    },
    {
      field: '含税金额',
      width: '150px',
    },
    {
      field: '不含税金额',
      width: '150px',
    },
    {
      field: '税额',
      width: '150px',
    },
    {
      field: '来源单号',
      width: '150px',
    },
    {
      field: '备注',
      width: '150px',
    },
    {
      field: '备注',
      width: '150px',
    },
  ]; //表格宽度配置
  taxRate: number = 13;
  customerContact: any;
  loadData: boolean;
  purchaseArrivalOrder: PurchaseArrivalOrder = {
    purchaseArrivalOrderId: 0, // 采购到货订单ID
    purchaseArrivalOrderNum: '', // 采购到货订单编号
    orderDate: null, // 订单日期
    supplyShortName: '', // 供应商简称
    supplyChineseName: '', // 供应商中文名
    supplyEnglishName: '', // 供应商英文名
    supplyContactName: '', // 供应商联系人姓名
    supplyContactId: 0, // 供应商联系人ID
    address: '', // 地址
    purchaseManName: '', // 采购员姓名
    purchaseManId: 0, // 采购员ID
    departmentName: '', // 部门名称
    departmentId: 0, // 部门ID
    actualArrivalDate: null, // 实际到货日期
    paoSettlementMethodId: 0, // 结算方式ID
    settlementMethodName: '', // 结算方式名称
    paoCurrencyId: 0, // 货币ID
    currencyName: '', // 货币名称
    paoCollectionPeriodId: 0, // 收款期限ID
    collectionPeriodName: '', // 收款期限名称
    remark: '', // 备注
    status: '', // 状态
    isClosed: false, // 是否关闭
    arrivalQuantity: 0, // 到货数量
    returnedQuantity: 0, // 退货数量
    totalTaxAmount: 0, // 税额
    totalAmountWithoutTax: 0, // 不含税总金额
    createDate: null, // 创建日期
    creator: '', // 创建者
    files: [], // 文件列表
    fileRemarks: [], // 文件备注
    purchaseArrivalOrderParts: [
      {
        purchaseArrivalOrderPartId: null, // 采购到货订单物料行ID
        partNum: '', // 物料编号
        partUOM: '', // 物料单位
        partName: '', // 物料名称
        description: '', // 物料描述
        partType: '', // 规格型号
        image: '', // 图片
        arrivalQuantity: 0, // 到货数量
        warehouseId: 0, // 仓库ID
        warehouseName: '', // 仓库名称
        warehouseNum: '', // 仓库编号
        positionId: 0, // 位置ID
        positionName: '', // 位置名称
        positionNum: '', // 位置编号
        arrivalDate: null, // 到货日期
        priceWithTax: 0, // 含税价格
        priceWithoutTax: 0, // 不含税价格
        taxRate: 0, // 税率
        amountWithTax: 0, // 含税金额
        amountWithoutTax: 0, // 不含税金额
        taxAmount: 0, // 税额
        alreadyReceivedQuantity: 0, // 已入库数
        returnedQuantity: 0, // 退货数量
        note: '', // 备注
        purchaseOrderNum: '', // 采购订单编号
        purchaseOrderPartId: 0, // 采购订单物料行ID
        paopPurchaseArrivalOrderId: 0, // 采购到货订单ID
        purchaseArrivalOrderNum: '', // 采购到货订单编号
        paoPartId: 0,
        isInspection: false,
      },
    ],
    paoSupplyId: 0,
    supplyNum: '',
    isArrival: false,
    alreadyReceivedQuantity: 0,
    totalaMountWithTax: 0,
    qrCodePath: '',
    qrCodeConfigurationId: 0,
    qrCodeConfigurationName: ''
  };
  purchaseArrivalOrderRules: { [key: string]: DValidateRules } = {
    purchaseArrivalNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*采购需求单单号不能为空' },
        { minlength: 2, message: '*采购需求单单号长度至少为2' },
        { maxlength: 40, message: '*采购需求单单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*采购需求单单号不能包含空格' },
      ],
    },
    purchaseManName: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*业务员不能为空' }],
    },
    advicePurchaseDate: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*建议申请时间不能为空' }],
    },
    partNum: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*物料不能为空' }],
    },
    purchaseDate: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*建议采购时间不能为空' }],
    },
    purchaseQuantity: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*建议采购数量不能为空' }],
    },
  };
  supplyContactOption = []; // 供应商联系人
  supplyContact = {}; //供应商联系人
  settlementMethodOption = []; // 结算方式
  settlementMethod = {}; //结算方式
  currencyOption = []; // 交易币种
  currency = {}; //交易币种
  collectionPeriodOption = []; // 付款账期
  collectionPeriod = {}; //付款账期
  fujianNumber: any = 0;
  warehouseData: any;
  options = [
    { label: '检验', value: true },
    { label: '不检验', value: false },
  ];
  QRCodeConfigs: any=[];
  QRCodeConfigoption={
    qrCodeConfigurationId:0,
    qrCodeConfigurationName:'',
    qrCodePath:''
  }
  constructor(
    private DialogService: DialogService,
    private Router: Router,
    private UserService: UserService,
    private PurchaseService: PurchaseService,
    private CustomerService: CustomerService,
    private DataSharingService: DataSharingService,
    private ActivatedRoute: ActivatedRoute,
    private EncodeRulesService: EncodeRulesService,
    private StorehouseService: StorehouseService,
    private MaterialService: MaterialService,
    private QrcodeconfigService:QrcodeconfigService
  ) {}
  ngOnInit(): void {
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.purchaseArrivalOrder.creator = JSON.parse(userinfoString).username;
    }
    this.CustomerService.GetPagedCurrency(1, 9999).subscribe((res: any) => {
      this.currencyOption = res.items;
    });
    this.CustomerService.GetPagedCollectionPeriod({
      PageSize: 999,
      PageNumber: 1,
      SearchStatus: '付款',
    }).subscribe((res: any) => {
      this.collectionPeriodOption = res.items;
    });
    this.QrcodeconfigService.getQRCodeConfigurations(
      '采购到货二维码配置',
      1,
      9999
    ).subscribe((res: any) => {
      this.QRCodeConfigs = res.items;
    });
    this.CustomerService.GetPagedSettlementMethod(1, 9999).subscribe(
      (res: any) => {
        this.settlementMethodOption = res.items;
      }
    );
    this.ActivatedRoute.params.subscribe((params: any) => {
      this.PurchaseService.getPurchaseArrivalById(params.id).subscribe(
        (res: any) => {
          this.purchaseArrivalOrder = res;
          this.purchaseArrivalOrder.purchaseArrivalOrderParts.forEach(
            (item: any) => {
              item.arrivalDate = new Date(item.arrivalDate);
              this.calculateAmount(item);
            }
          );
          this.purchaseArrivalOrder.orderDate = new Date(
            this.purchaseArrivalOrder.orderDate
          );
          this.purchaseArrivalOrder.actualArrivalDate = new Date(
            this.purchaseArrivalOrder.actualArrivalDate
          );
          this.purchaseArrivalOrder.actualArrivalDate = new Date(
            this.purchaseArrivalOrder.actualArrivalDate
          );
          this.fujianNumber = this.purchaseArrivalOrder.files.length;
          this.supplyContact = {
            supplyContactId: this.purchaseArrivalOrder.supplyContactId,
            supplyContactName: this.purchaseArrivalOrder.supplyContactName,
          };
          this.currency = {
            currencyId: this.purchaseArrivalOrder.paoCurrencyId,
            currencyName: this.purchaseArrivalOrder.currencyName,
          };
          this.settlementMethod = {
            settlementMethodId: this.purchaseArrivalOrder.paoSettlementMethodId,
            settlementMethodName:
              this.purchaseArrivalOrder.settlementMethodName,
          };
          this.collectionPeriod = {
            collectionPeriodId: this.purchaseArrivalOrder.paoCollectionPeriodId,
            collectionPeriodName:
              this.purchaseArrivalOrder.collectionPeriodName,
          };
          this.QRCodeConfigoption={
            qrCodeConfigurationId:this.purchaseArrivalOrder.qrCodeConfigurationId,
            qrCodeConfigurationName:this.purchaseArrivalOrder.qrCodeConfigurationName,
            qrCodePath:this.purchaseArrivalOrder.qrCodePath
          }
        }
      );
    });
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  addRow() {
    this.purchaseArrivalOrder.purchaseArrivalOrderParts.push({
      purchaseArrivalOrderPartId: 0, // 采购到货订单物料行ID
      partNum: '', // 物料编码
      partUOM: '', // 物料单位
      partName: '', // 物料名称
      description: '', // 物料描述
      partType: '', // 规格型号
      image: '', // 图片
      arrivalQuantity: 0, // 到货数量
      warehouseId: 0, // 仓库ID
      warehouseName: '', // 仓库名称
      warehouseNum: '', // 仓库编号
      positionId: 0, // 位置ID
      positionName: '', // 位置名称
      positionNum: '', // 位置编号
      arrivalDate: null, // 到货日期
      priceWithTax: 0, // 含税价格
      priceWithoutTax: 0, // 不含税价格
      taxRate: 0, // 税率
      amountWithTax: 0, // 含税金额
      amountWithoutTax: 0, // 不含税金额
      taxAmount: 0, // 税额
      alreadyReceivedQuantity: 0, // 已接收数量
      returnedQuantity: 0, // 退货数量
      note: '', // 备注
      purchaseOrderNum: '', // 采购订单编号
      purchaseOrderPartId: 0, // 采购订单物料行ID
      paopPurchaseArrivalOrderId: 0, // 采购到货订单ID
      purchaseArrivalOrderNum: '', // 采购到货订单编号
      paoPartId: 0,
      isInspection: false,
    });
  } //添加行
  addRowA(item: any, index: any) {
    const newItem = JSON.parse(JSON.stringify(item));
    newItem.purchaseArrivalOrderPartId = 0;
    newItem.arrivalDate = new Date(newItem.arrivalDate) || new Date();
    newItem.arrivalQuantity = 0; // 将 arrivalQuantity 设置为 0
    this.purchaseArrivalOrder.purchaseArrivalOrderParts.splice(
      index + 1,
      0,
      newItem
    );
    this.calculateAmount(newItem);
  } //添加行
  deleteRow(index: number) {
    this.purchaseArrivalOrder.purchaseArrivalOrderParts.splice(index, 1);
    if (this.purchaseArrivalOrder.purchaseArrivalOrderParts.length == 0) {
      this.addRow();
    }
    this.calculateTotalAmount();
  }
  isStartApproval: boolean = false;
  isStartApprovalChange() {
    this.isStartApproval = true;
  }
  submit($event: any) {
    if ($event.valid) {
      if (!this.validatePurchaseArrival(this.purchaseArrivalOrder)) {
        return;
      }
      this.PurchaseService.editPurchaseArrival(
        this.purchaseArrivalOrder.purchaseArrivalOrderId,
        this.purchaseArrivalOrder,
        this.purchaseArrivalOrder.qrCodeConfigurationId
      ).subscribe(
        (res: any) => {
          this.showToast('success', '成功', '提交成功');
          setTimeout(() => {
            this.cancel();
          }, 1000);
        },
        (error) => {
          if (error.status == 404) {
            this.showToast('error', '失败', '服务器连接失败');
          } else {
            this.showToast('error', '失败', error.error);
          }
        }
      );
    } else {
      this.showToast('warn', '错误', '请检查表单是否填写正确');
    }
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + url);
    return urls;
  }
  cancel() {
    this.Router.navigateByUrl('/pages/purchase/purchase-arrival');
  }
  fujian(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '采购到货单附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '销售附件',
        urls: this.purchaseArrivalOrder.files,
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseArrivalOrder.files.push(
              results.modalContentInstance.urls
            );
            this.fujianNumber = this.purchaseArrivalOrder.files.length;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  validatePurchaseArrival(purchaseArrival: PurchaseArrivalOrder): boolean {
    for (const [
      index,
      item,
    ] of purchaseArrival.purchaseArrivalOrderParts.entries()) {
      if (!item.partNum) {
        this.showToast('warn', '错误', `第${index + 1}行物料编码不能为空`);
        return false;
      }
      if (item.arrivalQuantity <= 0) {
        this.showToast('warn', '错误', `第${index + 1}行数量必须大于0`);
        return false;
      }
    }
    return true;
  } //所有验证通过
  selectUser() {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择业务员',
      content: SelectUserComponent,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseArrivalOrder.purchaseManName =
              results.modalContentInstance.selectData.name;
            this.purchaseArrivalOrder.purchaseManId =
              results.modalContentInstance.selectData.id;
            this.UserService.GetDepartmentById(
              results.modalContentInstance.selectData.departmentId
            ).subscribe((res: any) => {
              this.purchaseArrivalOrder.departmentName = res.name;
              this.purchaseArrivalOrder.departmentId = res.departmentId;
            });
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectDepartment() {
    if (!this.purchaseArrivalOrder.purchaseManId) {
      this.showToast('warn', '请选择业务员', '请选择业务员');
    }
  }
  selectSupply() {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择供应商',
      content: SelectSupplierComponent,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseArrivalOrder.supplyShortName =
              results.modalContentInstance.selectData.supplyShortName;
              this.purchaseArrivalOrder.supplyNum = results.modalContentInstance.selectData.supplyNum;
            this.purchaseArrivalOrder.paoSupplyId =
              results.modalContentInstance.selectData.supplyId;
            this.purchaseArrivalOrder.supplyChineseName =
              results.modalContentInstance.selectData.supplyChineseName;
            this.purchaseArrivalOrder.supplyEnglishName =
              results.modalContentInstance.selectData.supplyEnglishName;
            this.supplyContactOption =
              results.modalContentInstance.selectData.supplyContacts;
            this.purchaseArrivalOrder.purchaseManName =
              results.modalContentInstance.selectData.salesmanName;
            this.purchaseArrivalOrder.purchaseManId =
              results.modalContentInstance.selectData.salesmanId;
            this.UserService.GetUserById(
              results.modalContentInstance.selectData.salesmanId
            ).subscribe((res: any) => {
              this.purchaseArrivalOrder.departmentId = res.departmentId;
              this.UserService.GetDepartmentById(res.departmentId).subscribe(
                (res: any) => {
                  this.purchaseArrivalOrder.departmentName = res.name;
                }
              );
            });
            this.purchaseArrivalOrder.supplyContactId =
              results.modalContentInstance.selectData.supplyContacts.find(
                (contact: { isDefault: boolean }) => contact.isDefault === true
              )?.supplyContactId;
            this.purchaseArrivalOrder.supplyContactName =
              results.modalContentInstance.selectData.supplyContacts.find(
                (contact: { isDefault: boolean }) => contact.isDefault === true
              )?.supplyContactName;
            results.modalInstance.hide();
            this.supplyContact = {
              supplyContactId: this.purchaseArrivalOrder.supplyContactId,
              supplyContactName: this.purchaseArrivalOrder.supplyContactName,
            };
            this.currency = {
              currencyId:
                results.modalContentInstance.selectData.supplyCurrencyId,
              currencyName:
                results.modalContentInstance.selectData.currencyName,
            };
            this.settlementMethod = {
              settlementMethodId:
                results.modalContentInstance.selectData
                  .supplySettlementMethodId,
              settlementMethodName:
                results.modalContentInstance.selectData.settlementMethodName,
            };
            this.collectionPeriod = {
              collectionPeriodId:
                results.modalContentInstance.selectData
                  .supplyCollectionPeriodId,
              collectionPeriodName:
                results.modalContentInstance.selectData.collectionPeriodName,
            };
            this.purchaseArrivalOrder.paoSettlementMethodId =
              results.modalContentInstance.selectData.supplySettlementMethodId;
            this.purchaseArrivalOrder.settlementMethodName =
              results.modalContentInstance.selectData.settlementMethodName;
            this.purchaseArrivalOrder.paoCurrencyId =
              results.modalContentInstance.selectData.supplyCurrencyId;
            this.purchaseArrivalOrder.currencyName =
              results.modalContentInstance.selectData.currencyName;
            this.purchaseArrivalOrder.paoCollectionPeriodId =
              results.modalContentInstance.selectData.supplyCollectionPeriodId;
            this.purchaseArrivalOrder.collectionPeriodName =
              results.modalContentInstance.selectData.collectionPeriodName;
            this.purchaseArrivalOrder.purchaseArrivalOrderParts = [];
            this.addRow();
            this.purchaseArrivalOrder.purchaseArrivalOrderParts.map(
              (item: any) => {
                this.calculateAmount(item);
              }
            );
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectSupplier() {
    if (this.purchaseArrivalOrder.purchaseArrivalOrderParts[0].partNum) {
      const results = this.DialogService.open({
        id: 'dialog-service',
        maxHeight: '400px',
        width: '300px',
        backdropCloseable: true,
        data: '',
        dialogtype: 'warning',
        html: true,
        content:
          '<div style="color:#8a6d3b;font-size: 14px;">确定切换供应商，这将会使您构建的物料行数据重置！</div>',
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              results.modalInstance.hide();
              this.selectSupply();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    } else {
      this.selectSupply();
    }
  }
  selectSupplyContact($event: any) {
    this.purchaseArrivalOrder.supplyContactId = $event.supplyContactId;
    this.purchaseArrivalOrder.supplyContactName = $event.supplyContactName;
  }
  selectcurrency($event: any) {
    this.purchaseArrivalOrder.paoCurrencyId = $event.currencyId;
    this.purchaseArrivalOrder.currencyName = $event.currencyName;
  }
  selectsettlementMethodOption($event: any) {
    this.purchaseArrivalOrder.paoSettlementMethodId = $event.settlementMethodId;
    this.purchaseArrivalOrder.settlementMethodName =
      $event.settlementMethodName;
  }
  selectcollectionPeriodOption($event: any) {
    this.purchaseArrivalOrder.paoCollectionPeriodId = $event.collectionPeriodId;
    this.purchaseArrivalOrder.collectionPeriodName =
      $event.collectionPeriodName;
  }
  taxRateChange(rowitem: any, value: number) {
    rowitem.taxRate = value / 100;
    this.calculateAmount(rowitem);
  } //税率改变
  quantityChange(rowitem: any, value: number) {
    rowitem.alreadyReceivedQuantity = value;
    rowitem.arrivalQuantity = value;
    this.calculateAmount(rowitem);
  } //采购数量改变
  priceWithTaxChange(rowitem: any, value: number) {
    rowitem.priceWithTax = value;
    this.calculateAmount(rowitem);
  } //含税单价改变
  calculateAmount(item: any): void {
    //计算不含税单价，并保留6位小数
    item.priceWithoutTax = +(item.priceWithTax / (1 + item.taxRate)).toFixed(4);
    item.amountWithTax = +(item.priceWithTax * item.arrivalQuantity).toFixed(4);
    item.taxAmount = +(
      (item.priceWithTax - item.priceWithoutTax) *
      item.arrivalQuantity
    ).toFixed(4);
    item.amountWithoutTax = +(item.amountWithTax - item.taxAmount).toFixed(4);
    this.calculateTotalAmount();
  }
  calculateTotalAmount(): void {
    this.purchaseArrivalOrder.arrivalQuantity =
      this.purchaseArrivalOrder.purchaseArrivalOrderParts.reduce((pre, cur) => {
        return pre + cur.arrivalQuantity;
      }, 0);
    this.purchaseArrivalOrder.alreadyReceivedQuantity =
      this.purchaseArrivalOrder.arrivalQuantity;
    this.purchaseArrivalOrder.totalaMountWithTax =
      this.purchaseArrivalOrder.purchaseArrivalOrderParts.reduce((pre, cur) => {
        return pre + cur.amountWithTax;
      }, 0);
    this.purchaseArrivalOrder.totalAmountWithoutTax =
      this.purchaseArrivalOrder.purchaseArrivalOrderParts.reduce((pre, cur) => {
        return pre + cur.amountWithoutTax;
      }, 0);
    this.purchaseArrivalOrder.totalTaxAmount =
      this.purchaseArrivalOrder.purchaseArrivalOrderParts.reduce((pre, cur) => {
        return pre + cur.taxAmount;
      }, 0);
  }
  selectPurchaseOrder(dialogtype?: string) {
    const purchaseOrderPartIds =
      this.purchaseArrivalOrder.purchaseArrivalOrderParts.map(
        (item: { purchaseOrderPartId: any }) => item.purchaseOrderPartId
      );
    const Supply = this.purchaseArrivalOrder.supplyChineseName;
    const results = this.DialogService.open({
      id: 'Add',
      width: '1200px',
      backdropCloseable: true,
      data: { purchaseOrderPartIds: purchaseOrderPartIds, Supply: Supply },
      title: '选择采购订单',
      content: SelectPurchaseOrderComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (
              results.modalContentInstance.CheckedRows.every(
                (
                  item: { poSupplyId: any },
                  index: any,
                  array: { poSupplyId: any }[]
                ) => item.poSupplyId === array[0].poSupplyId
              )
            ) {
              this.purchaseArrivalOrder.paoSupplyId =
                results.modalContentInstance.CheckedRows[0].poSupplyId;
              this.purchaseArrivalOrder.supplyShortName =
                results.modalContentInstance.CheckedRows[0].supplyShortName;
                this.purchaseArrivalOrder.supplyNum = results.modalContentInstance.CheckedRows[0].supplyNum;
              this.purchaseArrivalOrder.supplyChineseName =
                results.modalContentInstance.CheckedRows[0].supplyChineseName;
              this.purchaseArrivalOrder.supplyEnglishName =
                results.modalContentInstance.CheckedRows[0].supplyEnglishName;
              this.purchaseArrivalOrder.supplyContactName =
                results.modalContentInstance.CheckedRows[0].supplyContactName;
              this.purchaseArrivalOrder.supplyContactId =
                results.modalContentInstance.CheckedRows[0].supplyContactId;
              this.supplyContact = {
                supplyContactId: this.purchaseArrivalOrder.supplyContactId,
                supplyContactName: this.purchaseArrivalOrder.supplyContactName,
              };
              this.purchaseArrivalOrder.purchaseManName =
                results.modalContentInstance.CheckedRows[0].purchaseManName;
              this.purchaseArrivalOrder.purchaseManId =
                results.modalContentInstance.CheckedRows[0].purchaseManId;
              this.purchaseArrivalOrder.departmentName =
                results.modalContentInstance.CheckedRows[0].departmentName;
              this.purchaseArrivalOrder.departmentId =
                results.modalContentInstance.CheckedRows[0].departmentId;
              this.purchaseArrivalOrder.paoSettlementMethodId =
                results.modalContentInstance.CheckedRows[0].supplySettlementMethodId;
              this.purchaseArrivalOrder.settlementMethodName =
                results.modalContentInstance.CheckedRows[0].settlementMethodName;
              this.purchaseArrivalOrder.paoCurrencyId =
                results.modalContentInstance.CheckedRows[0].supplyCurrencyId;
              this.purchaseArrivalOrder.currencyName =
                results.modalContentInstance.CheckedRows[0].currencyName;
              this.purchaseArrivalOrder.paoCollectionPeriodId =
                results.modalContentInstance.CheckedRows[0].supplyCollectionPeriodId;
              this.purchaseArrivalOrder.collectionPeriodName =
                results.modalContentInstance.CheckedRows[0].collectionPeriodName;
              this.purchaseArrivalOrder.purchaseArrivalOrderParts =
                this.purchaseArrivalOrder.purchaseArrivalOrderParts.filter(
                  (item: any) => item.paoPartId !== 0 && item.paoPartId !== null
                );
              // 将 CheckedRows 映射为 purchaseArrivalOrderParts 的对象格式并添加
              const newPurchaseArrivalOrderParts =
                results.modalContentInstance.filterRows.map((item: any) => {
                  return {
                    purchaseArrivalOrderPartId: 0, // 采购到货订单物料行ID
                    partNum: item.partNum, // 物料编号
                    partUOM: item.partUOM, // 物料单位
                    partName: item.partName, // 物料名称
                    description: item.description || '', // 物料描述
                    partType: item.partType, // 规格型号
                    image: item.image, // 图片
                    arrivalQuantity:
                      item.purchaseQuantity - item.deliveryQuantity, // 到货数量
                    unarrivalQuantity:
                      item.purchaseQuantity - item.deliveryQuantity, // 未到货数量
                    warehouseId: 0, // 仓库ID
                    warehouseName: '', // 仓库名称
                    warehouseNum: '', // 仓库编号
                    positionId: 0, // 位置ID
                    positionName: '', // 位置名称
                    positionNum: '', // 位置编号
                    arrivalDate: new Date(), // 到货日期
                    priceWithTax: item.priceWithTax, // 含税价格
                    priceWithoutTax: item.priceWithoutTax, // 不含税价格
                    taxRate: item.taxRate, // 税率
                    amountWithTax: 0, // 含税金额
                    amountWithoutTax: 0, // 不含税金额
                    taxAmount: 0, // 税额
                    paoPartId: item.poPartId, // 物料ID
                    returnedQuantity: 0, // 退货数量
                    note: item.note, // 备注
                    purchaseOrderNum: item.purchaseOrderNum, // 采购订单编号
                    purchaseOrderPartId: item.purchaseOrderPartId, // 采购订单物料行ID
                    paopPurchaseArrivalOrderId: 0, // 采购到货订单ID
                    purchaseArrivalOrderNum: '', // 采购到货订单编号
                    isInspection: item.isInspection,
                  };
                });
              this.purchaseArrivalOrder.purchaseArrivalOrderParts =
                this.purchaseArrivalOrder.purchaseArrivalOrderParts.concat(
                  newPurchaseArrivalOrderParts
                );
              if (
                this.purchaseArrivalOrder.purchaseArrivalOrderParts.length == 0
              ) {
                this.addRow();
              }
              results.modalInstance.hide();
              this.purchaseArrivalOrder.purchaseArrivalOrderParts.forEach(
                (part) => {
                  this.MaterialService.getPartById(part.paoPartId).subscribe(
                    (res: any) => {
                      part.positionId = res.positionID;
                      part.warehouseId = res.warehouseID;
                      this.StorehouseService.getWarehouseById(
                        res.warehouseID
                      ).subscribe((res: any) => {
                        part.warehouseName = res.warehouseName;
                        part.warehouseNum = res.warehouseNum;
                      });
                      this.StorehouseService.GetPositionById(
                        res.positionID
                      ).subscribe((res: any) => {
                        part.positionName = res.positionName;
                        part.positionNum = res.positionNum;
                      });
                      this.calculateAmount(part);
                    }
                  );
                  this.calculateAmount(part);
                }
              );
            } else {
              this.showToast('warn', '错误', '请选择相同供应商的采购订单');
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectWarehouse(rowitem: any) {
    if (rowitem) {
      if (!rowitem.partNum) {
        this.showToast('warn', '错误', '没有物料数据');
        return;
      }
    }
    const results = this.DialogService.open({
      id: 'Add',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择仓库',
      content: SelectStorehouseComponent,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            rowitem.warehouseId =
              results.modalContentInstance.selectData.warehouseId;
            rowitem.warehouseName =
              results.modalContentInstance.selectData.warehouseName;
            rowitem.warehouseNum =
              results.modalContentInstance.selectData.warehouseNum;
            rowitem.positionId = null;
            rowitem.positionName = null;
            rowitem.positionNum = null;
            this.warehouseData = results.modalContentInstance.selectData;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectPosition(rowItem: any, dialogtype?: string) {
    if (rowItem.warehouseId == 0) {
      return;
    }
    let data = {
      display: false,
      warehouseData: this.warehouseData,
      warehouseId: rowItem.warehouseId,
      placeholder: '请选择库位',
    };
    const results = this.DialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width: '1000px',
      data: data,
      title: '选择仓位',
      content: SelectPositionComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {
              rowItem.positionName =
                results.modalContentInstance.selectData.positionName;
              rowItem.positionNum =
                results.modalContentInstance.selectData.positionNum;
              rowItem.positionId =
                results.modalContentInstance.selectData.positionId;
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectQRCodeConfigoption($event: any) {
    this.purchaseArrivalOrder.qrCodeConfigurationId = $event.qrCodeConfigurationId;
    this.purchaseArrivalOrder.qrCodeConfigurationName =
      $event.qrCodeConfigurationName;
  }
}
